#
#===============================================================================
#
#         FILE:  TinySong.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/19/2010 04:53:04 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::TinySong;

use LWP::UserAgent;

sub register {
    my $self = shift;

    return ('cmd' => 'tinysong', 'pat' => '^!tinysong\s+(.*)');
}

sub help {
    my $self = shift;

    return ('Returns the first result for a tinysong.com search');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    $msgtxt =~ /^!tinysong\s+(.*)/;

    my $search = $1;
    $search =~ s/[\s+]+/+/g;

    my $ua = LWP::UserAgent->new;
    my $res = $ua->get("http://www.tinysong.com/s/$search");

    if( ! $res->is_success ) {
	$kernel->post($sender => privmsg => $target => "Failed to connect to API");
	return;
    }

    my @results = split /\n/, $res->decoded_content;

    my @parsed = map {
        /^(http:\/\/.*); (\d*); (.*); (\d*); (.*); (\d*); (.*);$/ ;
        {
            tinysongLink    => $1,
            songID          => $2,
            songName        => $3,
            artistID        => $4,
            artistName      => $5,
            albumID         => $6,
            albumName       => $7,
        }
    } grep { !/^NSF;\s*$/ } map {chomp; split(/\n/, $_)} @results;
    
    if( ! scalar(@parsed) ) {
	$kernel->post($sender => privmsg => $target => "No results");
	return;
    }

    $kernel->post($sender => privmsg => $target =>
	    sprintf('%s by %s on album %s < %s >', 
		$parsed[0]{'songName'}, $parsed[0]{'artistName'},
		$parsed[0]{'albumName'} ? $parsed[0]{'albumName'} : 'N/A',
		$parsed[0]{'tinysongLink'}));
}

1;
